package service

import (
	"context"
	"errors"
	"fmt"

	v1 "server_go/api/v1"
	"server_go/internal/model"
	"server_go/internal/repository"
	"time"

	"golang.org/x/crypto/bcrypt"
	"gorm.io/gorm"
)

type UsersService interface {
	Login(ctx context.Context, req v1.UsersLoginRequest) (v1.UsersResponse, error)
}

func NewUsersService(
	service *Service,
	usersRepository repository.UsersRepository,
) UsersService {
	return &usersService{
		Service:         service,
		usersRepository: usersRepository,
	}
}

type usersService struct {
	*Service
	usersRepository repository.UsersRepository
}

func (s *usersService) Login(ctx context.Context, req v1.UsersLoginRequest) (v1.UsersResponse, error) {
	if req.Account == "" || req.Password == "" {
		return v1.UsersResponse{}, v1.ErrBadRequest
	}
	user, err := s.usersRepository.GetUsersByAccount(ctx, req.Account)
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return v1.UsersResponse{}, v1.ErrAdiminNotFound
		}
		return v1.UsersResponse{}, v1.ErrInternalServerError
	}

	if user.Type != model.UserType {
		return v1.UsersResponse{}, v1.ErrType
	}
	err = bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(req.Password))
	if err != nil {
		return v1.UsersResponse{}, v1.ErrPwd
	}
	fmt.Println(user)
	token, _ := s.jwt.GenToken(user.ID, time.Now().Add(time.Hour*24*7), user.Type)
	var info = v1.UsersResponse{
		ID:    user.ID,
		Token: token,
	}

	return info, nil
}
